package com.example.listener;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;



public class MyMessageListener implements MessageListener {

    private static Map<String, Consumer<String>> RULE = new HashMap<>();

    static {
        RULE.put(TopicChannel.SEND_EMAIL, MyMessageListener::sendEmail);
        RULE.put(TopicChannel.SEND_PHONE, MyMessageListener::sendPhone);
    }

    public static void sendEmail(String msg) {
        System.out.println("listen email:" + msg);
    }

    public static void sendPhone(String msg) {
        System.out.println("listen phone:" + msg);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        byte[] byteChannel = message.getChannel();
        byte[] byteBody = message.getBody();
        try {
            String channel = new String(byteChannel);
            String body = new String(byteBody);
            System.out.println("channel: + " + channel + ", body: " + body);
            RULE.get(channel).accept(body);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    
}
